package cn.tedu.mall.service;

import cn.tedu.mall.vo.ImageVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.Buffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    private String path = "D:/images/";
    @Override
    public ImageVO uploadFile(MultipartFile uploadFile) throws IOException {
        String fileName = uploadFile.getOriginalFilename();
        fileName = fileName.toLowerCase();
        if (!fileName.matches(".+(.jpeg|.jpg|.gif|.png)$")) {
            return ImageVO.fail();
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width <= 0 || height <= 0) {
                return ImageVO.fail();
            }
            String datePath = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
            String fileLocalPath = path + datePath;
            File fileDir = new File(fileLocalPath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            String realFileName = uuid + fileType;
            String realPathFile = fileLocalPath + realFileName;
            uploadFile.transferTo(new File(realPathFile));
            String url = "https://ts1.cn.mm.bing.net/th/id/R-C.c2656bd56d27b85fccfceb307298f28e?rik=vfgjAHxsh7UiSA&riu=http%3a%2f%2fimage.digitalinsightresearch.in%2fuploads%2fimagelibrary%2fcbr%2fjava.jpg&ehk=vn97rntDxEtOc3Cbaz4ljrRGWJJhTekLa6AxVl8q%2bDU%3d&risl=&pid=ImgRaw&r=0";
            return ImageVO.success(url,width,height);
        } catch (Exception e) {
            e.printStackTrace();
            return ImageVO.fail();
        }

    }
}
